package com.example.passwordmanager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import com.Ohuang.ilivedata.LiveDataBus;
import com.Ohuang.ilivedata.MyLiveData;
import com.example.passwordmanager.Util.QMUIDialogUtil;
import com.example.passwordmanager.databinding.ActivityListBinding;
import com.example.passwordmanager.db.AppDatabase;
import com.example.passwordmanager.db.UserBean;
import com.example.util.base_util.ClipboardUtils;
import com.qmuiteam.qmui.recyclerView.QMUIRVItemSwipeAction;
import com.qmuiteam.qmui.recyclerView.QMUISwipeAction;
import com.qmuiteam.qmui.recyclerView.QMUISwipeViewHolder;
import com.qmuiteam.qmui.skin.QMUISkinManager;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ListActivity extends BaseActivity {
    private ActivityListBinding activityListBinding;
    private RecyclerView recyclerView;
    private Adapter mAdapter;
    private MutableLiveData<List<UserBean>> liveData = new MutableLiveData<>();
    private LiveData<List<UserBean>> listLiveData;
    private ExecutorService executorService;
    private List<UserBean> userBeanList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityListBinding = ActivityListBinding.inflate(getLayoutInflater());
        setContentView(activityListBinding.getRoot());
        recyclerView = activityListBinding.rvList;
        executorService = Executors.newSingleThreadExecutor();

        initView();
        initEvent();
    }

    private void initView() {
        activityListBinding.imageAdd.setOnClickListener(v -> {
            showSimpleBottomSheetList(
                    false, false, false, false);

        });


        activityListBinding.searchView.setSubmitButtonEnabled(true);
        activityListBinding.searchView.setIconifiedByDefault(false);
        searchViewEvent();


        QMUIRVItemSwipeAction swipeAction = new QMUIRVItemSwipeAction(true, new QMUIRVItemSwipeAction.Callback() {
            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
//                mAdapter.remove(viewHolder.getAdapterPosition());
            }

            @Override
            public int getSwipeDirection(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
                return QMUIRVItemSwipeAction.SWIPE_LEFT;
            }

            @Override
            public void onClickAction(QMUIRVItemSwipeAction swipeAction, RecyclerView.ViewHolder selected, QMUISwipeAction action) {
                super.onClickAction(swipeAction, selected, action);

                if (action == mAdapter.mDeleteAction) {
                    showDeleteDialog(userBeanList.get(selected.getAdapterPosition()).getId());//弹出对话框

                }
                if (action == mAdapter.mWriteReviewAction) {
                    executorService.execute(new Runnable() {
                        @Override
                        public void run() {
                            UserBean userBean = AppDatabase.getInstance(getApplicationContext())
                                    .getUserDao()
                                    .getUserById(userBeanList.get(selected.getAdapterPosition()).getId());
                            LiveDataBus.get().with("startPsdActivity", UserBean.class).postValue(userBean);
                        }
                    });


                }
                swipeAction.clear();
            }
        });
        swipeAction.attachToRecyclerView(recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this) {
            @Override
            public RecyclerView.LayoutParams generateDefaultLayoutParams() {
                return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
            }
        });

        mAdapter = new Adapter(ListActivity.this);
        recyclerView.setAdapter(mAdapter);

    }

    @Override
    protected void KeyboardIsHide() {
        super.KeyboardIsHide();
        activityListBinding.searchView.clearFocus();
    }

    private void searchViewEvent() {
        activityListBinding.searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                if (handler.hasMessages(1)) {
                    handler.removeMessages(1);
                }
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        listLiveData = AppDatabase.getInstance(getApplicationContext()).getUserDao().vagueSearchForName(query);
                        ListActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                listLiveData.observeForever(new Observer<List<UserBean>>() {
                                    @Override
                                    public void onChanged(List<UserBean> userBeans) {
                                        liveData.postValue(userBeans);
                                    }
                                });
                            }
                        });
                    }
                });

                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                if (handler.hasMessages(1)) {
                    handler.removeMessages(1);
                }
                if (TextUtils.isEmpty(newText)) {
                    loadAllData();
                } else {
                    Message message = new Message();
                    message.what = 1;
                    message.obj = newText;
                    handler.sendMessageDelayed(message, 1000);

                }
                return false;
            }
        });
    }


    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 1:
                    String sName = (String) msg.obj;
                    executorService.execute(new Runnable() {
                        @Override
                        public void run() {
                            listLiveData = AppDatabase.getInstance(getApplicationContext()).getUserDao().vagueSearchForName(sName);
                            ListActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    listLiveData.observeForever(new Observer<List<UserBean>>() {
                                        @Override
                                        public void onChanged(List<UserBean> userBeans) {
                                            liveData.postValue(userBeans);
                                        }
                                    });
                                }
                            });
                        }
                    });
                    break;

                default:
                    break;
            }

            return true;
        }
    });

    private void initEvent() {

        loadAllData();

        liveData.observe(this, new Observer<List<UserBean>>() {
            @Override
            public void onChanged(List<UserBean> userBeans) {
                userBeanList = userBeans;
                mAdapter.setData(userBeanList);
                if (userBeanList.size() == 0) {
                    activityListBinding.emptyView.show("你还没有数据", "点击左下角按钮添加");
                } else {
                    activityListBinding.emptyView.hide();
                }
            }
        });
        LiveDataBus.get().with("showDialog", String.class).observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                final QMUITipDialog tipDialog = new QMUITipDialog.Builder(ListActivity.this)
                        .setTipWord(s)
                        .create();
                tipDialog.show();
                activityListBinding.imageAdd.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        tipDialog.dismiss();
                    }
                }, 1500);
            }
        });


        LiveDataBus.get().with("startPsdActivity", UserBean.class).observe(this, new Observer<UserBean>() {
            @Override
            public void onChanged(UserBean userBean) {
                Intent intent = new Intent(ListActivity.this, PsdActivity.class);
                intent.putExtra("isAdd", false);
                startActivity(intent);
                MyLiveData.getInstance().with("UserBean", UserBean.class)
                        .setValue(userBean);//传参
            }
        });

    }

    private void loadAllData() {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                listLiveData = AppDatabase.getInstance(getApplicationContext()).getUserDao().loadLiveDataOfAllUser();
                ListActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        listLiveData.observeForever(new Observer<List<UserBean>>() {
                            @Override
                            public void onChanged(List<UserBean> userBeans) {
                                liveData.postValue(userBeans);
                            }
                        });
                    }
                });
            }
        });
    }


    private void showDeleteDialog(int id) {
        QMUIDialogUtil.showMessageNegativeDialog(this, "删除", "是否删除该账号?", new QMUIDialogAction.ActionListener() {
            @Override
            public void onClick(QMUIDialog dialog, int index) {
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        AppDatabase.getInstance(getApplicationContext()).getUserDao().deleteUserBean(new UserBean(id));
                    }
                });
                dialog.dismiss();
            }
        });

    }


    // ================================ 生成不同类型的BottomSheet
    private void showSimpleBottomSheetList(boolean gravityCenter,
                                           boolean addCancelBtn,
                                           boolean allowDragDismiss,
                                           boolean withMark) {
        QMUIBottomSheet.BottomListSheetBuilder builder = new QMUIBottomSheet.BottomListSheetBuilder(this);
        builder.setGravityCenter(gravityCenter)
                .setSkinManager(QMUISkinManager.defaultInstance(this))
                .setAddCancelBtn(addCancelBtn)
                .setAllowDrag(allowDragDismiss)
                .setNeedRightMark(withMark)
                .setOnSheetItemClickListener(new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                    @Override
                    public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
                        dialog.dismiss();
                        switch (position) {
                            case 0:
                                Intent intent = new Intent(ListActivity.this, PsdActivity.class);
                                intent.putExtra("isAdd", true);
                                startActivity(intent);
                                break;
                            case 1:
                                Intent intent2 = new Intent(ListActivity.this, SetActivity.class);
                                startActivity(intent2);
                                break;
                        }
                    }
                });
        if (withMark) {
            builder.setCheckedIndex(40);
        }

        builder.addItem("添加数据");
        builder.addItem("设置");

        builder.build().show();
    }


    class Adapter extends RecyclerView.Adapter<QMUISwipeViewHolder> {

        private List<UserBean> mData = new ArrayList<>();

        final QMUISwipeAction mDeleteAction;
        final QMUISwipeAction mWriteReviewAction;

        public Adapter(Context context) {
            QMUISwipeAction.ActionBuilder builder = new QMUISwipeAction.ActionBuilder()
                    .textSize(QMUIDisplayHelper.sp2px(context, 14))
                    .textColor(Color.WHITE)

                    .paddingStartEnd(QMUIDisplayHelper.dp2px(context, 14));

            mDeleteAction = builder.text("删除").backgroundColor(Color.RED).build();
            mWriteReviewAction = builder.text("编辑").backgroundColor(0xFF00A5FF).build();
        }

        public void setData(@Nullable List<UserBean> list) {
            mData.clear();
            if (list != null) {
                mData.addAll(list);
            }
            notifyDataSetChanged();
        }

        public void remove(int pos) {
            mData.remove(pos);
            notifyItemRemoved(pos);
        }

        public void add(int pos, UserBean item) {
            mData.add(pos, item);
            notifyItemInserted(pos);
        }

        public void prepend(@NonNull List<UserBean> items) {
            mData.addAll(0, items);
            notifyDataSetChanged();
        }

        public void append(@NonNull List<UserBean> items) {
            mData.addAll(items);
            notifyDataSetChanged();
        }

        @NonNull
        @Override
        public QMUISwipeViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_user, parent, false);
            final QMUISwipeViewHolder vh = new QMUISwipeViewHolder(view);
            vh.addSwipeAction(mDeleteAction);
            vh.addSwipeAction(mWriteReviewAction);

            return vh;
        }

        @Override
        public void onBindViewHolder(@NonNull QMUISwipeViewHolder holder, @SuppressLint("RecyclerView") int position) {
            TextView textView_name = holder.itemView.findViewById(R.id.tv_name);
            TextView textView_username = holder.itemView.findViewById(R.id.tv_username);
            TextView textView_psd = holder.itemView.findViewById(R.id.tv_password);
            ImageView imageView_copy_user = holder.itemView.findViewById(R.id.img_copy_user);
            ImageView imageView_copy_psd = holder.itemView.findViewById(R.id.img_copy_psd);
            CheckBox checkBox_show = holder.itemView.findViewById(R.id.checkbox_show);
            CardView cardView = holder.itemView.findViewById(R.id.cardView);
            TextView tv_go2fa=holder.itemView.findViewById(R.id.tv_go2fa);
            UserBean userBean = mData.get(position);
            if (TextUtils.isEmpty(userBean.getSecretKey())){
                tv_go2fa.setVisibility(View.GONE);
            }else {
                tv_go2fa.setVisibility(View.VISIBLE);
                tv_go2fa.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Get2FACodeActivity.start(ListActivity.this,userBean.getName(),userBean.getSecretKey());
                    }
                });
            }
            textView_name.setText(mData.get(position).getName());
            textView_username.setText(mData.get(position).getUsername());
            textView_psd.setText("********");
            cardView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new Thread(() -> {
                        UserBean userBean = AppDatabase.getInstance(getApplicationContext())
                                .getUserDao()
                                .getUserById(mData.get(position).getId());
                        MyLiveData.getInstance().with("showPsd", UserBean.class).postValue(userBean);
                    }).start();
                    startActivity(new Intent(ListActivity.this, ShowPsdActivity.class));
                }
            });
            imageView_copy_psd.setOnClickListener(v -> {
                ClipboardUtils.copyText(mData.get(position).getPassword(), ListActivity.this);
                Toast.makeText(ListActivity.this, "已复制到粘贴板", Toast.LENGTH_SHORT).show();
            });

            imageView_copy_user.setOnClickListener(v -> {
                ClipboardUtils.copyText(mData.get(position).getUsername(), ListActivity.this);
                Toast.makeText(ListActivity.this, "已复制到粘贴板", Toast.LENGTH_SHORT).show();
            });

            checkBox_show.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        textView_psd.setText(mData.get(position).getPassword());
                    } else {
                        textView_psd.setText("********");
                    }
                }
            });

        }

        @Override
        public int getItemCount() {
            return mData.size();
        }
    }

    private Long time = 0L;

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - time < 2000) {
            super.onBackPressed();
        } else {
            time = System.currentTimeMillis();
            Toast.makeText(ListActivity.this, "再按一下退出程序", Toast.LENGTH_SHORT).show();
        }
    }
}